import React from 'react';
import Button from "../../../../node_modules/react-bootstrap/lib/Button";
import ListGroup from "react-bootstrap/lib/ListGroup";
import ListGroupItem from "react-bootstrap/lib/ListGroupItem";
//import Input from "react-bootstrap/lib/Input";
import LeftNav from '../../../../node_modules/material-ui/lib/left-nav';
import Path from '../../lib/path.js';
import Modal from "../../../../node_modules/react-bootstrap/lib/Modal";
import EventProxy from '../../lib/eventproxy.js';
//import List from "../component/List.jsx";
import HttpRequest from './../HttpRequest.js';
import DropdownButton from 'react-bootstrap/lib/DropdownButton';
import MenuItem from 'react-bootstrap/lib/MenuItem';
import List from "../component/List.jsx";
import Form from '../../src/component/formElement/Form.jsx';
import Label from '../../src/component/formElement/Label.jsx'
import Input from '../../src/component/formElement/Input.jsx'
import Selector from '../../src/component/formElement/Selector.jsx'
import SelectList from '../../src/component/formElement/SelectList.jsx'


var product_configs = [];
var BuildManagementTab = React.createClass({
    getInitialState: function () {
        return ({
            open: false,
            current_project: this.props.current_project, //当前项目
            ListData: [], //构建配置数据
            ListItems: [], //左侧构建配置列表
            productConfigs: [], //当前选中构建配置中包含的产品配置
            current_selected: null //当前选中配置

        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_project: newProps.current_project,
            current_selected: null
        }, function () {
            this.componentWillMount();
        });
    },
    componentWillMount: function () {
        HttpRequest.getAllBuildConfigs(this.state.current_project._id).success(function (configs) {
            if (configs.code == 0) {
                var listData = _.remove(configs.data, function (o) {
                    return o.project == this.state.current_project._id;
                }.bind(this));
                this.setState({
                    ListData: listData
                }, this._renderList)
            }
        }.bind(this)).error(function (err) {

        });
    },

    itemSelected: function (config) {
        HttpRequest.getBuildConfigInfo(config._id).success(function (res) {
            if (res.code == 500) {
                toastr.error(null, res.message);
            } else {
                this.setState({
                    current_selected: res.data,
                    productConfigs: res.data.product_configs
                });
            }
        }.bind(this)).error(function (err) {
            toastr.error(null, JSON.stringify(err));
        });

    },
    _renderList: function () {
        var items = [];
        this.setState({
            List: <List ListData={this.state.ListData}
                        ItemStyle={{cursor: "pointer"}}
                        SelectedItemStyle={{background:"f3f3f3",cursor: "pointer"}}
                        onItemSelected={this.itemSelected}
                        itemDeleted={this.removeBuildConfig}
                        ifEmpty={<span style={{color:"#969696",paddingLeft:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>该项目没有构建配置！ </span>}
                        IconMap={[
                            {type:"mk_back",icon:<img src="/res/image/MK_h.png" style={{marginTop:"-5px"}}/>},
                            {type:"app_android",icon:<img src="/res/image/iphone_h.png"/>},
                            {type:"app_ios",icon:<img src="/res/image/iphone_h.png" />},
                            {type:"app_plugin",icon:<i className="fa fa-plug" style={{fontSize:"23px"}} aria-hidden="true"/>}
                        ]}
            />
        });
        if (this.state.ListData.length > 0) {
            this.setState({
                current_selected: this.state.ListData[this.state.ListData.length - 1]
            })
        }
    },
    removeBuildConfig: function (config_id) {
        confirm("确定删除？", function () {
            HttpRequest.deleteBuildConfig(config_id).success(function (resp) {
                if (resp.code != 500) {
                    this.componentWillMount();
                } else {
                    toastr.error(null, "删除失败");
                }
            }.bind(this)).error(function () {
                toastr.error(null, "删除失败");
            });
        }.bind(this));
    },
    addConfig: function (event, eventKey) {
        var count = 0;
        var t_count = 0;
        if (count == 0) {
            count = "";
        }
        if (t_count == 0) {
            t_count = "";
        }
        this.state.ListData.map(function (item) {
            if (item.name == "new_" + eventKey + "_buildConfig" + count) {
                count++;
            }
            if (item.title == "新建构建配置" + t_count) {
                t_count++;
            }
        });
        var name = "new_" + eventKey + "_buildConfig" + count;
        var title = "新建构建配置" + t_count;
        var newConfig = {
            "name": name,
            "title": title,
            "type": eventKey,
            "project": this.state.current_project._id,
            "product_configs": []
        }

        HttpRequest.addBuildConfig(newConfig).success(function (resp) {
            if (resp.code != 500) {
                this.componentWillMount();
            } else {
                toastr.error(null, "新建构建配置失败：" + resp.message);
            }
        }.bind(this)).error(function (err) {
            toastr.error(null, "新建构建配置失败");
        });

    },
    saveEdit: function (data) {
        HttpRequest.updateBuildConfig(data).success(function (resp) {
            if (resp.code != 500) {
                this.componentWillMount();
                toastr.success(null, "新建构建配置成功");
            } else {
                toastr.error(null, "修改构建配置失败：" + resp.message);
            }
        }.bind(this)).error(function (err) {
            toastr.error(null, "修改构建配置失败");
        });
    },
    render: function () {
        var content_pageRight = null;
        if (this.state.ListData.length > 0) {
            content_pageRight = <BuildConfigDetail
                saveEdit={this.saveEdit}
                current_selected={this.state.current_selected}
                current_project={this.state.current_project}/>
        } else {
            content_pageRight = <div style={{textAlign:"center"}}>
                <div style={{color:"#969696",marginTop:"50px",fontSize:"14px",fontFamily:'Microsoft YaHei'}}>
                    <i className="fa fa-exclamation-circle"
                       style={{fontSize:"48px",cursor:"pointer"}}/>
                    <br/>
                    该项目没有构建配置！
                </div>
            </div>
        }
        return (
            <div style={{height:"100%"}}>
                <div className="content_pageLeft">
                    <span className="info_title" style={{paddingLeft:"30px"}}>构建配置</span>
                    <DropdownButton bsStyle="primary"
                                    style={{backgroundColor:"#555",height: "25px",paddingTop: "2px"}}
                                    onSelect={this.addConfig}
                                    title="新建" id="new_product_config">
                        <MenuItem eventKey="mk_back">mk产品构建</MenuItem>
                        <MenuItem eventKey="app_android">Android产品构建</MenuItem>
                        <MenuItem eventKey="app_ios">IOS产品构建</MenuItem>
                        <MenuItem eventKey="app_plugin">移动插件产品构建</MenuItem>
                    </DropdownButton>
                    <div style={{overflowY:"auto",height:"100%",maxHeight:"90%",marginTop:"5px"}}>
                        {this.state.List}
                    </div>


                </div>
                <div className="content_pageRight">
                    <span className="info_title">配置详情</span>
                    <div style={{width:"100%",height:"calc(100% - 63px)",marginTop: "20px"}}>
                        {content_pageRight}
                    </div>
                </div>

            </div>
        );
    }

});
export default BuildManagementTab;

//产品配置选择列表
var ProductConfigsList = React.createClass({
    getInitialState: function () {
        return ({
            current_project: this.props.current_project,
            current_selected: this.props.current_selected,
            product_configs: [],
            ListItems: []
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_project: newProps.current_project,
            current_selected: newProps.current_selected
        }, function () {
            this.componentWillMount();
        });
    },

    componentWillMount: function () {
        var ob = this;
        var pdct_configs = [];
        HttpRequest.getAllProductConfigs(ob.state.current_project._id).success(function (configs) {
            if (configs.code == 0) {
                configs.data.map(function (item) {
                    if (item.type == this.state.current_selected.type) {
                        for (var it in this.state.current_selected.product_configs) {
                            if (this.state.current_selected.product_configs[it] == item._id) {
                                item['checked'] = true;
                                break;
                            } else {
                                item['checked'] = false;
                            }
                        }
                        pdct_configs.push(item);
                    }
                }.bind(this));
                product_configs = pdct_configs;
                ob.setState({
                    product_configs: pdct_configs
                }, ob._renderList)
            }
        }.bind(this)).error(function (err) {
            toastr.error(null, "获取产品配置失败");
        });
    },
    itemSelected: function (item, index) {
        document.getElementById("dis_select_all").src = "/res/image/check.png";
        document.getElementById("select_all").src = "/res/image/check.png";
        item["checked"] = !item["checked"];
        this._renderList();
    },
    _renderList: function () {
        var items = [];
        this.state.product_configs.map(function (item, index) {
            var checkbox = "/res/image/check.png";
            if (item.checked) {
                checkbox = "/res/image/check_h.png";
            }
            items.push(
                <div className="selector_item"
                     key={index}
                     id={"selection_"+index}
                     onClick={this.itemSelected.bind(this,item,index)}>
                    <span style={{width:"20px",height:"20px",display:"inline-block"}}><img src={checkbox}/></span>
                    <span style={{marginLeft:"10px"}}>{item.name}</span>
                </div>
            )
        }.bind(this));
        this.setState({
            ListItems: items
        });
    },
    handleClose: function () {
        this.setState({open: false});
    },
    handleOpen: function () {
        this.setState({open: true});
    },
    handleComplete: function () {
        //buildcfg list
        var selected = [];
        this.state.product_configs.map(function (item) {
            if (item.checked) {
                selected.push(item);
            }
        });
        this.props.getSelected(selected);
        this.handleClose();
    },
    search: function () {
        var input = document.getElementById("buildcfg_search_input").value;
        var configs = product_configs;
        var configsFiltered = [];
        if (input.length > 0) {
            for (var i = 0; i < configs.length; i++) {
                if (configs[i].name.indexOf(input) >= 0) {
                    configsFiltered.push(configs[i]);
                }

            }
        } else {
            configsFiltered = configs;
        }
        this.setState({
            product_configs: configsFiltered,
        }, this._renderList);
    },
    disSelectAll: function () {
        var chec = document.getElementById("dis_select_all").src;
        if (chec == "/res/image/check_h.png") {
            document.getElementById("dis_select_all").src = "/res/image/check.png";
        } else {
            document.getElementById("select_all").src = "/res/image/check.png";
            document.getElementById("dis_select_all").src = "/res/image/check_h.png";
        }

        var product_configs = this.state.product_configs;
        product_configs.map(function (item) {
            item.checked = false;
        });
        this.setState({
            product_configs: product_configs
        }, this._renderList);
    },
    selectAll: function () {
        var chec = document.getElementById("select_all").src;
        if (chec == "/res/image/check_h.png") {
            document.getElementById("select_all").src = "/res/image/check.png";
        } else {
            document.getElementById("dis_select_all").src = "/res/image/check.png";
            document.getElementById("select_all").src = "/res/image/check_h.png";
        }
        var product_configs = this.state.product_configs;
        product_configs.map(function (item) {
            item.checked = true;
        });
        this.setState({
            product_configs: product_configs
        }, this._renderList);
    },
    render: function () {
        return (
            <div>
                <Modal
                    show={this.state.open}
                    style={{borderRadius:"0"}}
                >
                    <Modal.Header style={{background:"#383F45"}}>
                        <Modal.Title style={{color:"white"}}>
                            <img src="/res/image/select.png" style={{float:"left"}}/>
                            <span style={{marginLeft: "10px",letterSpacing:"2px"}}>选择</span>
                            <img src="/res/image/close.png" style={{float:"right",cursor:"pointer",marginTop:" 5.5px"}}
                                 onClick={this.handleClose}/>
                        </Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <div>
                            <div
                                style={{width:"460px",height:"35px",border:"solid 1px lightgray",marginBottom:"18px"}}>
                                <input type="text" placeholder="输入您要搜索的内容" id="buildcfg_search_input"
                                       onChange={this.search}
                                       style={{width: "420px",height:"30px",border: "none",float: "left",outline: "none",paddingLeft:"20px"}}/>
                            <span className="glyphicon glyphicon-search"
                                  style={{float:"right",height:"20px",width: "20px",marginTop: "6px",marginRight: "10px",fontSize:"20px",marginBottom: "auto"}}
                                  aria-hidden="true"/>
                            </div>
                            <div className="selector_dialog_body">
                                {this.state.ListItems}
                            </div>
                        </div>
                        <div style={{ fontFamily:'Microsoft YaHei',fontSize:"15px",marginTop:"10px"}}>
                            <span onClick={this.selectAll} style={{cursor:"pointer"}}>
                                <span style={{width:"20px",height:"20px",display:"inline-block"}}>
                                    <img id="select_all" src="/res/image/check.png"/>
                                </span>
                                <span style={{marginLeft:"10px"}}>全选</span>
                                </span>
                            <span onClick={this.disSelectAll} style={{cursor:"pointer"}}>
                                <span style={{width:"20px",height:"20px",display:"inline-block",marginLeft:"20px"}}>
                                    <img id="dis_select_all" src="/res/image/check.png"/>
                                </span>
                                <span style={{marginLeft:"10px"}}>全不选</span>
                            </span>
                        </div>
                    </Modal.Body>
                    <Modal.Footer style={{borderTop:"none"}}>
                        <Button
                            onClick={this.handleComplete}
                            style={{backgroundColor: "#383F45", borderColor: "#383F45",width:"70px"}}
                            bsStyle="primary">完成</Button>
                    </Modal.Footer>
                </Modal>
            </div>
        )
    }

});

var BuildConfigDetail = React.createClass({
    getInitialState: function () {
        return ({
            current_selected: this.props.current_selected,
            current_project: this.props.current_project
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_selected: newProps.current_selected,
            current_project: newProps.current_project
        });
    },

    update: function (data) {
        this.props.saveEdit(data);
    },
    render: function () {

        return (
            <div style={{height:"100%"}}>
                <Edit_config
                    update={this.update}
                    current_selected={this.state.current_selected}
                    current_project={this.state.current_project}/>
            </div>
        )
    }
});
var Edit_config = React.createClass({
    getInitialState: function () {
        return ({
            current_selected: this.props.current_selected,
            current_project: this.props.current_project,
            productConfigs: [],
            form_data: {}
        });
    },

    componentWillReceiveProps: function (newProps) {
        this.setState({
            current_selected: newProps.current_selected,
            current_project: newProps.current_project,
            form_data: {
                name: newProps.current_selected.name,
                title: newProps.current_selected.title
            }
        }, function () {
            this.componentDidMount();
        });
    },

    componentDidMount: function () {
        var thisOb = this;
        var productConfigs = [];
        if (this.state.current_selected) {
            var ep = new EventProxy();
            var product_configs = this.state.current_selected.product_configs;
            ep.fail(function (err) {
                toastr.error(null, "获取配置信息出现错误");
            });
            ep.after('product_config_found', product_configs.length, function () {
                thisOb.setState({
                    productConfigs: productConfigs
                });
            });
            product_configs.map(function (config) {
                HttpRequest.getProductConfigById(config).success(function (resp) {
                    if (resp.code != 500) {
                        productConfigs.push(resp.data);
                        ep.emit('product_config_found');
                    } else {
                        toastr.error(null, "获取构建配置信息失败！");
                    }
                }).error(()=> {
                    toastr.error(null, "获取构建配置信息失败！");
                });
            });
        }
    },
    editProductConfig: function (configSelected) {
        var config = [];
        var config_ids = [];
        configSelected.map(function (item) {
            config_ids.push(item._id);
            config.push(item);
        });
        var current_selected = this.state.current_selected;
        current_selected.product_configs = config_ids;
        this.setState({
            current_selected: current_selected,
            productConfigs: config
        });
    },
    saveEdit: function () {
        var product_configs = [];
        this.state.productConfigs.map(function (product_config) {
            product_configs.push(product_config._id);
        });
        var buildConfigInfo = {
            product_configs: product_configs,
            name: this.refs['name'].getValue(),
            title: this.refs['title'].getValue(),
            type: this.refs['type'].getValue(),
            project: this.state.current_project._id
        };
        var data = {
            "config_info": buildConfigInfo,
            "config_id": this.state.current_selected._id
        };
        this.props.update(data);

    },

    executeBuilding: function () {
        var data = {
            config: this.state.current_selected._id
        };
        toastr.success(null, '构建任务发起中...');
        HttpRequest.executeBuilding(data).success(function (resp) {
            if (resp.code != 500) {
                console.log(resp._id);
                toastr.success(null, '构建任务发起成功');
            } else {
                toastr.error(null, '构建发起失败');
            }
        }).error(function () {
            toastr.error(null, '构建发起失败');
        });
    },
    formDataChange: function () {
        this.setState({
            form_data: {
                name: this.refs['name'].getValue(),
                title: this.refs['title'].getValue()
            }
        })
    },
    render: function () {
        var config_info;
        var productConfigs = this.state.productConfigs;
        var productConfigsName = "";
        productConfigs.map(function (config) {
            productConfigsName = productConfigsName + config.name + ";";
        });

        if (this.state.current_selected) {
            config_info = this.state.current_selected;
            var icon;
            switch (config_info.type) {
                case "mk_back":
                    icon = <image src="/res/image/MK_h.png"
                                  style={{lineHeight:"40px",marginRight:"5px",marginTop:"-5px"}}/>;
                    break;
                case "app_android":
                    icon = <image src="/res/image/iphone_h.png"
                                  style={{lineHeight:"40px",marginRight:"5px",marginTop:"-5px"}}/>;
                    break;
                case "app_ios":
                    icon = <image src="/res/image/iphone_h.png"
                                  style={{lineHeight:"40px",marginRight:"5px",marginTop:"-5px"}}/>;
                    break;
                case "app_plugin":
                    icon = <i className="fa fa-plug" style={{fontSize:"23px"}} aria-hidden="true"/>
            }
        } else {
            return (
                <div></div>
            );
        }
        return (
            <div style={{height:"100%"}}>
                <div id="cfg_detail_edit" style={{height:"100%",overflowY:"auto"}}>
                    <div style={{height:"100%",minWidth:"530px", maxWidth:"770px",width:"97%"}}>
                        <Label defaultValue={config_info.type} ref="type" title="配置类型"
                               icon={icon}/>
                        <Label defaultValue={this.state.current_project.title} title="所属项目"/>
                        <Input defaultValue={this.state.form_data.name} ref="name" title="配置名称"
                               onBlur={this.formDataChange}/>
                        <Input defaultValue={this.state.form_data.title} ref="title" title="配置标题"
                               onBlur={this.formDataChange}/>
                        <Selector ref="project" defaultValue={productConfigs}
                                  openSelectDialog={()=>{this.refs["product_configs_edit"].handleOpen()}} title="选择配置"/>

                        <div onClick={()=>{this.saveEdit()}}
                             style={{cursor:"pointer",width: "70px",height: "30px",fontSize:"13px",backgroundColor:"#303c40",padding:" 6px 16px",float:"right",marginRight:"20px"}}>
                            <span style={{letterSpacing: "2px",marginLeft:"5px",color:"white"}}>保存</span>
                        </div>
                        <div onClick={()=>{this.executeBuilding()}}
                             style={{cursor:"pointer",width: "70px",height: "30px",fontSize:"13px",backgroundColor:"#303c40",padding:" 6px 16px",float:"right",marginRight:"30px"}}>
                            <span style={{letterSpacing: "2px",marginLeft:"5px",color:"white"}}>构建</span>
                        </div>
                    </div>
                </div>
                <ProductConfigsList ref="product_configs_edit"
                                    getSelected={this.editProductConfig}
                                    current_project={this.state.current_project}
                                    current_selected={this.state.current_selected}
                                    callback={this.editProductConfig}/>
            </div>
        )
    }
});

